import base64
import hashlib
import sys


def get_input(prompt, default="null", required=False):
    value = input(prompt)
    if required and not value:
        print(f"错误: {prompt.strip()} 为必填项")
        sys.exit(1)
    return value if value else default


def generate_signature(secret_key, app_id, sequence_no, timestamp, api_code, body):
    # Base64 encode the body
    body_encoded = base64.b64encode(body.encode()).decode()

    # Create the concatenated string
    concat_string = f'Body={body_encoded}&X-App-Id={app_id}&X-Sequence-No={sequence_no}&X-Timestamp={timestamp}&X-Api-Code={api_code}&{secret_key}'

    # Print the concatenated string
    print(f"\n拼接字符串:\n{concat_string}")

    # Generate SHA-256 hash
    sha256_hash = hashlib.sha256(concat_string.encode()).digest()

    # Base64 encode the SHA-256 hash
    signature = base64.b64encode(sha256_hash).decode()

    return signature


def main():
    # Get inputs
    secret_key = get_input("输入密钥: ", required=True)
    app_id = get_input("输入 X-App-Id (不输入则为null): ")
    sequence_no = get_input("输入 X-Sequence-No (不输入则为null): ")
    timestamp = get_input("输入 X-Timestamp (不输入则为null): ")
    api_code = get_input("输入 X-Api-Code: ", required=True)
    body = get_input("输入body (不输入则为null): ")

    # 生成签名
    signature = generate_signature(secret_key, app_id, sequence_no, timestamp, api_code, body)

    print(f"\n生成签名 (base64 编码): {signature}")


if __name__ == "__main__":
    main()
